package com.yanghui.lingyue.functions

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.bridge.SikaGroupEvent
import com.icedata.sika.bridge.SikaUserEvent
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.yanghui.lingyue.bot.Bot
import com.yanghui.lingyue.data.Command
import java.util.*
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read

object Repeat : AbstractFunction() {
    override val name = "Repeat"
    val repeatList = LinkedList<String>()
    private val repeatListLock = ReentrantReadWriteLock()

    init {
        repeatList.add("呜呜呜")
    }

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent)
            return command
        event as SikaGroupEvent
        if (event.sendGroup.id !in enableGroup)
            return command

        val isRepeat = false
        val message = event.message.contentToString()
        val group = Bot.groupList[event.sendGroup.id]
        val groupCache = group!!.groupCache
        if (message in repeatList) {
            repeatListLock.read {
                if (!(groupCache["SuccessiveRepeat"] as Boolean)
                    && (message == groupCache["LastMessage"])
                ) {
                    command.add(Command(event, "TEXT: $message", "", -1))
                    groupCache["SuccessiveRepeat"] = true
                }
                if (!isRepeat) {
                    // 如果不是复读状态，那么就退出禁止复读模式
                    groupCache["SuccessiveRepeat"] = false
                }
            }
        }
        groupCache["LastMessage"] = message
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        return CommandProcessor.Result.ADOPT
    }

    override fun filter(command: Command): Boolean {
        return false
    }
}